﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace StarryEdge.WPF.Tool
{
    /// <summary>
    /// 跨线程帮助类
    /// </summary>
    public class ThreadHelper
    {
        /// <summary>
        /// 异步跨线程
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="action"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Task<T> CrossThreadAsync<T>(Func<T, Task<T>> action, T value) => Application.Current.Dispatcher.InvokeAsync(() => action?.Invoke(value)).Result;

        /// <summary>
        /// 同步跨线程
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="action"></param>
        /// <param name="value"></param>
        public static void CrossThread<T>(Action<T> action, T value) => Application.Current.Dispatcher.Invoke(() => action?.Invoke(value));

        /// <summary>
        /// 判断是否是UI线程
        /// </summary>
        /// <param name="action">是UI线程则执行此委托</param>
        /// <param name="uiaction">非UI线程执行此方法</param>
        public static Task<object> IsUIThread(Func<Task<object>> action, Func<Task<object>> uiaction)
        {
            if (Thread.CurrentThread.ManagedThreadId == Application.Current.Dispatcher.Thread.ManagedThreadId)
            {
                return action.Invoke();
            }
            else
            {
                return uiaction.Invoke();
            }
        }
    }
}
